<template>
  <div class="run-modal-style">
    <Form :model="modelForm" ref="resourceForm" :rules="rules" :label-width="80">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item :label="$t('module.resourceManage.resCode')" prop="resourceCode">
            <!-- <Input placeholder="界面资源输入编码，接口资源输入请求路径" v-model="modelForm.resourceCode" ></Input> -->
            <Input
              v-model.trim="modelForm.resourceCode"
              :data="searchResult"
              @on-search="onSearch"
              @on-change="onChange"
              @on-select="onSelectSearch"
              @on-clear="onClear"
              :placeholder="$t('module.resourceManage.enterResourceCode')"
              icon="md-search"
              clearable
              :disabled="isShowCode == true"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item :label="$t('module.resourceManage.resName')" prop="resourceName">
            <Input placeholder v-model="modelForm.resourceName"  :disabled="isSelected"></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item :label="$t('module.resourceManage.resourceType')" prop="resourceType">
            <Select
              v-model="modelForm.resourceType"
              :transfer="true"
              
              :disabled="isSelected"
            >
              <Option
                :value="1"
                :key="1"
                :disabled="!canCreateUI"
              >{{$t('module.resourceManage.uiResource')}}</Option>
              <Option
                :value="2"
                :key="2"
                :disabled="!canCreateAPI"
              >{{$t('module.resourceManage.apiResource')}}</Option>
              <!-- <Option :value="3" :key="3" :disabled="!canCreateFunc">功能权限</Option> -->
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item :label="$t('module.valueSet.ownnerapp')" prop="applicationId">
            <Input placeholder v-model="applicationName"  disabled></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item :label="$t('common.status')" prop="enabled">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1" :disabled="isSelected">{{$t('common.enable')}}</Radio>
              <Radio :label="0" :disabled="isSelected">{{$t('common.disable')}}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;" v-if="modelForm.resourceType == 2">
          <Form-item :label="$t('module.valueSet.isPublic')" prop="publicFlag">
            <RadioGroup v-model="modelForm.publicFlag" size="small">
              <Radio :label="1" :disabled="isSelected">
                <span>{{this.$t("module.valueSet.public")}}</span>
              </Radio>
              <Radio :label="2" :disabled="isOnlyPublic || isSelected">
                <span>{{this.$t("module.valueSet.notpublic")}}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import { updateResource, addResource, queryResouceListForCode } from "@/api/resourceApi.js";
import locales from "./locales.js";
import { searchDelayTime } from "@/const.js";
import { resourceCodeReg } from "@/const.js";

export default {
  name: "ResourceEdit",
  mixins: [locales],
  props: {
    applicationId: {
      type: String,
      default() {
        return "";
      }
    },
    applicationName: {
      type: String,
      default() {
        return "";
      }
    },
    functionId: {
      type: String,
      default() {
        return "";
      }
    },
    id: {
      type: String,
      default() {
        return "";
      }
    },
    parentResourceId: {
      type: String,
      default() {
        return "";
      }
    },
    resourceObj: {
      type: Object,
      default() {
        return null;
      }
    },
    canCreateUI: {
      type: Boolean,
      default() {
        return true;
      }
    },
    canCreateAPI: {
      type: Boolean,
      default() {
        return true;
      }
    },
    canCreateFunc: {
      type: Boolean,
      default() {
        return true;
      }
    },
    isOnlyPublic: {
      type: Boolean,
      default() {
        return false;
      }
    },
    isShowCode: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  data() {
    const validateResourceCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.resourceManage.enterCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!this.isSelected && this.isResourceCodeExist) {
        callback(new Error(this.$t("module.resourceManage.resourceCodeTip")));
      } else if (!new RegExp(resourceCodeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      // 资源编码自动转大写
      this.modelForm.resourceCode = this.modelForm.resourceCode.toUpperCase();
      callback();
    };
    const validateResourceName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.resourceManage.enterName")));
      } else if (value != value.trim()) {
        callback(new Error(this.$t("module.resourceManage.noBlank")));
      } else if (value.length > 50) {
        callback(new Error(this.$t("module.resourceManage.resNameMaxFifty")));
      }
      callback();
    };
    return {
      modelForm: {
        applicationId: this.applicationId,
        functionId: this.functionId,
        id: this.id,
        parentResourceId: this.parentResourceId,
        resourceCode: "",
        resourceName: "",
        resourceType: 0,
        publicFlag: this.isOnlyPublic ? 1 : 2,
        enabled: 1
      },
      rules: {
        resourceCode: [{ validator: validateResourceCode, trigger: "blur", required: true }],
        resourceName: [{ validator: validateResourceName, trigger: "blur", required: true }]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          theme: "primary",
          handle: () => {
            this.$emit("Close");
          }
        }
      ],
      searchValue: "",
      searchResult: [],
      searchResultResource: [],
      selectedResource: null,
      pressCount: 0,
      isSelected: false,
      isResourceCodeExist: false
    };
  },
  created: function() {
    this.init();
    if (this.id) {
      this.$emit("SetTitle", this.$t("module.resourceManage.editRes"));
    } else {
      this.$emit("SetTitle", this.$t("module.resourceManage.creatRes"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    init() {
      if (this.resourceObj != null) {
        this.modelForm.resourceCode = this.resourceObj.resourceCode;
        this.modelForm.resourceName = this.resourceObj.resourceName;
        this.modelForm.resourceType = this.resourceObj.resourceType;
        this.modelForm.publicFlag = this.resourceObj.publicFlag;
        this.modelForm.enabled = this.resourceObj.enabled;
      } else if (this.canCreateUI) {
        this.modelForm.resourceType = 1;
      } else if (this.canCreateAPI) {
        this.modelForm.resourceType = 2;
      } else {
        this.modelForm.resourceType = 3;
      }
    },
    save() {
      this.$refs["resourceForm"].validate(valid => {
        if (valid) {
          // this.actions[0].loading = true;
          if (this.modelForm.id) {
            // $store
            updateResource(this.modelForm)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.resourceManage.editSuccess"),
                  duration: 3
                });
                //关闭当前窗口
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = true;
              });
          } else {
            addResource(this.modelForm).then(response => {
              this.$message.success({
                content: this.$t("module.resourceManage.createSuccess"),
                duration: 3
              });
              this.modelForm.id = response.data;
              //刷新树
              //关闭当前窗口
              this.$emit("Close", this.modelForm);
            });
          }
        } else {
          this.$message.error({
            content: $t("common.formValidateFailed"),
            duration: 3
          });
        }
      });
    },
    onChange(value) {
      console.log("in onChange " + value);
      if (value) {
        // 改变选择的资源时
        if (this.selectedResource && this.selectedResource.resourceCode != value) {
          // 清空选择的资源
          this.isSelected = false;
          this.selectedResource = null;
        }
      } else {
        // 清空时
        this.onClear();
      }
    },
    onSearch(value) {
      console.log("in onSearch " + value);
      // 编辑时不查询已有资源
      if (this.id) {
        return;
      }
      // 能创建API资源时才进行查询
      if (!this.canCreateAPI) {
        return;
      }
      this.searchResult = [];
      // 选择结果不再查询
      if (value && this.isSelected && this.selectedResource && this.selectedResource.resourceCode == value) {
        return;
      }

      this.isResourceCodeExist = false;
      if (value) {
        this.pressCount++;
        let param = {
          applicationId: this.applicationId,
          resourceCode: value,
          resourceType: 2,
          size: 10
        };
        // 延时查询
        setTimeout(() => {
          if (this.pressCount == 1) {
            this.pressCount = 0;
            // this.isShowSpin = true;
            // this.searchHint = "查询中...";
            queryResouceListForCode(param).then(({ data: records }) => {
              this.searchResultResource = records;
              if (records.length > 0) {
                // this.isShowSpin = false;
                // this.searchHint = "";
                records.forEach(resource => {
                  if (value == resource.resourceCode) {
                    this.$Modal.confirm({
                      title: this.$t("module.resourceManage.reuseResources"),
                      content: this.$t("module.resourceManage.reuseResourcesContent"),
                      onOk: () => {
                        this.onSelectSearch(value, true);
                      },
                      onCancel: () => {
                        this.isResourceCodeExist = true;
                        this.$refs["resourceForm"].validateField("resourceCode");
                      }
                    });
                  }
                  this.searchResult.push(resource.resourceCode);
                });
              } else {
                // this.isShowSpin = true;
                // this.searchHint = "无查询结果";
              }
            });
          } else {
            this.pressCount--;
          }
        }, searchDelayTime);
      }
    },
    onSelectSearch(value, isInput) {
      console.log("in onSelectSearch " + value);
      if (!isInput) {
        this.$message.error({
          content: this.$t("module.resourceManage.selectResourceContent"),
          duration: 5
        });
      }
      this.isSelected = true;
      this.selectedResource = this.searchResultResource.find(resource => {
        return resource.resourceCode == value;
      });
      // 表单设值
      this.modelForm.resourceCode = this.selectedResource.resourceCode;
      this.modelForm.resourceName = this.selectedResource.resourceName;
      this.modelForm.resourceType = this.selectedResource.resourceType;
      this.modelForm.publicFlag = this.selectedResource.publicFlag;
      this.modelForm.enabled = this.selectedResource.enabled;
      // 校验
      this.$refs["resourceForm"].validate();
    },
    onClear(value) {
      console.log("in onClear " + value);
      // 清空查询结果
      this.searchResult = [];
      this.searchResultResource = [];
      // 清空选择的资源
      this.isSelected = false;
      this.selectedResource = null;
    }
  },
  watch: {},
  directives: {}
};
</script>
